/**
 * @Author ZhangCuirong
 * @Date 2025/9/19 10:19
 * @description:
 */
public class Solution97 {
    public boolean isInterleave(String s1, String s2, String s3) {
        if (s1.length() + s2.length() != s3.length()) {
            return false;
        }
        boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];
        dp[0][0] = true;
        for (int i = 1; i <= s1.length(); i++) {
            if (s1.charAt(i - 1) == s3.charAt(i - 1)) {
                dp[i][0] = dp[i - 1][0];
            }
        }
        for (int i = 1; i <= s2.length(); i++) {
            if (s2.charAt(i - 1) == s3.charAt(i - 1)) {
                dp[0][i] = dp[0][i - 1];
            }
        }
        for (int i = 1; i <= s1.length(); i++) {
            for (int j = 1; j <= s2.length(); j++) {
                if (!dp[i][j] && s1.charAt(i - 1) == s3.charAt(i - 1 + j - 1 + 1) && dp[i - 1][j]) {
                    dp[i][j] = dp[i - 1][j];
                }
                if (!dp[i][j] && s2.charAt(j - 1) == s3.charAt(i - 1 + j - 1 + 1) && dp[i][j - 1]) {
                    dp[i][j] = dp[i][j - 1];
                }
            }
        }
        return dp[s1.length()][s2.length()];
    }

    public static void main(String[] args) {
        Solution97 solution = new Solution97();
        System.out.println(solution.isInterleave("aabcc", "dbbca", "aadbbcbcac"));//true
        System.out.println(solution.isInterleave("aabcc", "dbbca", "aadbbbaccc"));//false
        System.out.println(solution.isInterleave("", "", ""));//true
        System.out.println(solution.isInterleave("", "", "a"));//false
        System.out.println(solution.isInterleave("aabd", "adbc", "aabdbadc"));
        System.out.println(solution.isInterleave("a", "", "a"));//true
    }
}
